<template>
  <view >
    <form>
      <xmInfo
        :projectno="dataInfo.projectno"
        :projectname="dataInfo.projectname"
      ></xmInfo>

      <view class="cu-form-group">
        <view class="title"
          ><text class="cuIcon-favorfill text-xs text-red"></text>开始时间</view
        >
        <picker
          mode="date"
          :value="dataInfo.starttime ? dataInfo.starttime : date"
          start="2015-09-01"
          @change="DateChange('starttime', $event)"
        >
          <view class="picker">
            {{ dataInfo.starttime ? dataInfo.starttime : "请选择开始时间" }}
          </view>
        </picker>
      </view>
      <view class="cu-form-group">
        <view class="title"
          ><text class="cuIcon-favorfill text-xs text-red"></text>结束时间</view
        >
        <picker
          mode="date"
          :value="dataInfo.endtime ? dataInfo.endtime : date"
          start="2015-09-01"
          @change="DateChange('endtime', $event)"
        >
          <view class="picker">
            {{ dataInfo.endtime ? dataInfo.endtime : "请选择结束时间" }}
          </view>
        </picker>
      </view>
      <view class="cu-form-group">
        <view class="title">承包商</view>
        <view>{{ dataInfo.contractor }}</view>
      </view>
      <view class="cu-form-group" style="min-height: 0"></view>
      <view class="cu-bar bg-white">
        <view class="action"
          ><text class="cuIcon-favorfill text-xs text-red"></text>施工内容</view
        >
      </view>

      <view class="cu-form-group">
        <textarea
          v-model="dataInfo.remarks"
          maxlength="-1"
          :disabled="modalName != null"
          @input="textareaAInput"
          placeholder="请输入"
        ></textarea>
      </view>

      <view class="cu-form-group" style="min-height: 0"></view>
      <view class="cu-bar bg-white">
        <view class="action"
          ><text class="cuIcon-favorfill text-xs text-red"></text>图片上传</view
        >
      </view>
      <view class="cu-form-group">
        <!-- :deletable="!!id?false:true"
              :customBtn="!id?false:true" -->
        <js-uploadfile
          v-model="dataInfo.dataMap"
          :biz-key="dataInfo.id"
          biz-type="PmWeekly_image"
        ></js-uploadfile>
      </view>
      <view class="cu-card">
        <view
          class="cu-item shadow"
          v-for="(item,index) in dataInfo.pmWeeklyMaterialList"
          :key="item.id"
          v-if="item.status != 1"
        >
          <view class="cu-form-group padding">
            <!-- <view class="text-xl text-bold">材料名称</view> -->
            <view>
              <view style=" display: inline-block;padding: 5px;background: #3E97B0;color: #fff;width: 40px;text-align: center;font-style: italic;font-weight: bold">
                  {{ index + 1 }}
                </view>
            </view>
            <view class="text-xl text-bold">{{
              item["pmMaterial.mname"]
                ? item["pmMaterial.mname"]
                : item.pmMaterial.mname
            }}</view>
          </view>
		  <view class="cu-form-group">
		    <view class="text-xl ">材料编号</view>
		    <view class="text-xl ">{{ item.mcode }}</view>
		  </view>
		  <view class="cu-form-group">
		    <view class="text-xl ">剩余数量</view>
		    <view class="text-xl " style="text-align: right;flex: 1;">{{ item.syQty || '0' }}</view>
			 <view style="margin-left: 10px;">{{ item.unit }}</view>
		  </view>

          <view class="cu-form-group">
            <view class="text-xl text-bold"
              ><text class="cuIcon-favorfill text-xs text-red"></text
              >消耗数量</view
            >
            <input
              v-model="item.num"
              @input="updateItem(index, $event.target.value)"
              style="text-align: right;font-weight: bold;"
              type="digit"
              placeholder="请输入消耗数量"
              :custom-style="customStyle"
            />
			 <view style="margin-left: 10px;">{{ item.unit }}</view>
          </view>
         <!-- <view class="cu-form-group">
            <view class="title">单位</view>
            <view>{{ item.unit }}</view>
          </view> -->
          <view class="cu-bar bg-white">
            <view class="action"></view>
            <view>
              <text
                class="cuIcon-deletefill padding text-sl text-red"
                :data-pmid="item.pmid"
                @tap="DelItem"
              ></text>
            </view>
          </view>
        </view>
      </view>
      <view style="height: 180rpx" ></view>
      <view class="btn-group cu-bar foot cu-bar-footer" >
        <button class="cu-btn  shadow-blur" @click="addDetail" >
          <text class="cuIcon-roundadd padding text-red text-xsl"></text
          >材料明细
        </button>
        <button class="cu-btn bg-green shadow-blur" @click="submit" >
          提交
        </button>
      </view>
    </form>
    <add-detail
	   ref="addref"
      :modalNameDetail="modalNameDetail"
      :pcode="dataInfo.projectno"
      @modalNameDetailEmit="modalNameDetailEmit"
      @checkedListEmit="checkedListEmit"
      v-if="showAddDetail"
    ></add-detail>
  </view>
</template>
<script>
import addDetail from "./addDetail.vue";
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: {
    addDetail,
    xmInfo,
  },
  data() {
    return {
      value: 200,
      switchA: false,
      date: new Date().toISOString().substring(0, 10),
      modalName: null,
      modalNameDetail: null,
      showAddDetail: false,
      dataInfo: {},
      xmInfo: {},
      showButton: true,
      isSubmitting: false,
      formRef: null,
      customStyle: {
        width: "100%",
        textAlign: "right",
      },
      flag: hasPermission('proj:weekly:pmWeekly:edit'),
      id: "",
      x: 650, //x坐标
      y: 650, //y坐标
      localNum: '', // 声明局部变量
    };
  },
  onLoad(e) {
    if (!!e.id) {
      this.showButton = true;
      this.getweeklyPmWeeklyForm({
        id: e.id,
      });
      this.id = e.id;
    }
    if (!!e.xm) {
      this.showButton = true;
      this.xmInfo = JSON.parse(e.xm);
      this.dataInfo = this.xmInfo;
      console.log(this.dataInfo);
      this.getweeklyPmWeeklyForm({
        projectno: this.dataInfo.projectno,
      });
    }
  },
  methods: {
    updateItem(index, newNum) {
      console.log(index, newNum);
      const updatedItem = { ...this.dataInfo.pmWeeklyMaterialList[index], num: newNum };
      this.$set(this.dataInfo.pmWeeklyMaterialList, index, updatedItem);
      console.log(this.dataInfo.pmWeeklyMaterialList);
    },
    submit() {
      if (!this.dataInfo.starttime) {
        this.$u.toast("开始时间为必填项");
        return;
      }
      if (!this.dataInfo.endtime) {
        this.$u.toast("结束时间为必填项");
        return;
      }
      if (!this.dataInfo.remarks) {
        this.$u.toast("备注为必填项");
        return;
      }

      if (!this.dataInfo.dataMap || !this.dataInfo.dataMap.PmWeekly_image) {
        this.$u.toast("图片必传");
        return;
      }
      console.log(this.dataInfo.pmWeeklyMaterialList);
      // 验证数组dataInfo.pmWeeklyMaterialList是否有值，有值就验证每一项的num是否有值，全部有值才验证通过
      if (this.dataInfo.pmWeeklyMaterialList.length > 0) {
        let isValid = true;
        this.dataInfo.pmWeeklyMaterialList.forEach((item) => {
          if (!item.num && item.status != 1) {
            isValid = false;
          }
        });
        if (!isValid) {
          this.$u.toast("消耗数量必填");
          return;
        }
      }
      if (this.isSubmitting) {
        return;
      } else {
        this.isSubmitting = true;
        try {
          this.dataInfo.starttime = this.dataInfo.starttime
            ? this.dataInfo.starttime
            : this.date;
          this.dataInfo.endtime = this.dataInfo.endtime
            ? this.dataInfo.endtime
            : this.date;
          this.$u.api.zfgs.weeklyPmWeeklySave(this.dataInfo).then((res) => {
            if (res.result == "true") {
              this.$u.toast(res.message);
              const itemContent = {
                projectno: this.dataInfo.projectno,
                projectname: this.dataInfo.projectname,
              };
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 500);
            } else {
              this.$u.toast(res.message);
            }
          });
        } catch (error) {
          this.$u.toast(error.message);
        } finally {
          this.isSubmitting = false;
        }
      }
    },
    getweeklyPmWeeklyForm(params) {
      this.$u.api.zfgs
        .weeklyPmWeeklyForm({
          id: params.id == undefined ? "" : params.id,
          projectno: params.projectno == undefined ? "" : params.projectno,
        })
        .then((res) => {
          this.dataInfo = res.pmWeekly;
          this.dataInfo.projectname = this.dataInfo.projInfo.projectname
            ? this.dataInfo.projInfo.projectname
            : this.xmInfo.projectname;
          this.dataInfo.projectno = this.dataInfo.projInfo.projectno
            ? this.dataInfo.projInfo.projectno
            : this.xmInfo.projectno;
        });
    },
    DelItem(event) {
      const pmid = event.currentTarget.dataset.pmid;
      uni.showModal({
        title: "",
        content: "确定要删除吗？",
        cancelText: "取消",
        confirmText: "确认",
        success: (res) => {
          if (res.confirm) {
            this.dataInfo.pmWeeklyMaterialList.map((item) => {
              console.log(item, "item", pmid);
              if (item.pmid == pmid) {
                item.status = 1; //状态为1删除
                // 深度监听dataInfo.rectList
              }
            });
            this.$forceUpdate();
            console.log(this.dataInfo.pmWeeklyMaterialList);
            this.$u.toast("删除成功");
          }
        },
      });
    },
    SwitchA(e) {
      // this.switchA = e.detail.value
    },
    DateChange(item, e) {
      console.log(item, e);
      //   this.date = e.detail.value;
      if (item === "starttime") {
        this.dataInfo.starttime = e.detail.value;
      } else if (item === "endtime") {
        this.dataInfo.endtime = e.detail.value;
      }
      this.$forceUpdate();
    },
    textareaAInput(e) {
      this.dataInfo.dmark = e.detail.value;
    },
    addDetail() {
      this.showAddDetail = true;

      this.modalNameDetail = "DrawerModalR";
	  
	  this.$refs.addref.loadData()
	  this.$refs.addref.checkedList = []
	  
	  
	  
	  

      console.log(this.modalNameDetail, this.dataInfo, "dataInfo===");
    },
    modalNameDetailEmit(e) {
      this.modalNameDetail = e;
    },

    ViewImage(imageList, e) {
      uni.previewImage({
        urls: imageList,
        current: e.currentTarget.dataset.url,
      });
    },
    async checkedListEmit(e) {
      if (this.dataInfo.pmWeeklyMaterialList == undefined) {
        this.dataInfo.pmWeeklyMaterialList = [];
      }

      //   创建一个数组eArray，把传递过来的部分属性赋值给eArray
      let eArray = [];
      e.forEach((item) => {
        eArray.push({
          pmid: item.id,
          mcode: item.mcode,
          "pmMaterial.mname": item.mname,
          mstd: item.mstd,
          projectno: item.pcode,
          unit: item.unit,
          syQty: item.syQty,
        });
      });
      console.log(
        e,
        "checkedListEmit",
        this.dataInfo.pmWeeklyMaterialList,
        eArray
      );
      if (this.dataInfo.pmWeeklyMaterialList.length == 0) {
        this.dataInfo.pmWeeklyMaterialList = eArray;
      } else {
        // 创建一个新数组用于存放最终结果
        let newArray = [];

        // 遍历原始数据
        this.dataInfo.pmWeeklyMaterialList.forEach((originalItem) => {
          let matched = false; // 标记是否找到了匹配项

          // 遍历eArray
          eArray.forEach((updateItem) => {
            if (originalItem.pmid === updateItem.pmid) {
              // 找到匹配项，标记并保存更新后的项目
              matched = true;
              newArray.push(updateItem);
            }
          });

          // 如果没有在eArray中找到匹配项，则保留原始项目
          if (!matched) {
            newArray.push(originalItem);
          }
        });

        // 将eArray中未在原始列表中找到匹配pmid的项追加到newArray
        eArray.forEach((itemFromEArray) => {
          let exists = newArray.some(
            (item) => item.pmid === itemFromEArray.pmid
          );
          if (!exists) {
            newArray.push(itemFromEArray);
          }
        });

        // 最后，将处理后的数组赋值回原对象
        this.dataInfo.pmWeeklyMaterialList = newArray;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
$all_width: 140rpx;
$all_height: 140rpx;
.movable-area {
  z-index: 999;
  height: 97vh;
  width: 650rpx;
  // max-width: 1152rpx;
  // 固定在右边
  top: -150rpx;
  position: fixed;
  right: $all_width;
  // 固定在右下角
  pointer-events: none; //此处要加，鼠标事件可以渗透
  .movable-view {
    width: $all_width;
    height: $all_height;
    pointer-events: auto; //恢复鼠标事件
    .cu-bar {
      width: 320rpx;
    }
  }
}
.action {
  color: #303133;
}
.cu-form-group {
  flex-wrap: wrap;
}
.text-sl {
  font-size: 22px !important;
}
.cu-bar-footer {
  min-height: 80px;
}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  z-index: 997;
  background: #fff;
}
.green {
  color: green;
}
.text-xsl {
  font-size: 60rpx !important;
}
.flex-end {
  display: flex;
  justify-content: flex-end;
}
.sub-title {
  flex-grow: 1; /* 让右侧内容占据剩余空间 */
  max-width: 200px; /* 或其他合适的最大宽度，超过这个宽度时内容会换行 */
  word-break: break-word; /* 或 overflow-wrap: break-word; 允许单词在必要时断开以适应宽度 */
}
.text-xs {
  font-size: 18rpx !important;
}
.cu-item{
  border: 1px solid #39b54a;
}
</style>